#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include "extract.h"

#include <windows.h>
#include <shellapi.h>

int main(int argc, char *argv[])
{
	if (argc < 4)
		return -1;

	// argv[1] - updater.exe
	// argv[2] - input.upd
	// argv[3] - install.lst

	// read install list
	std::string line;
	std::vector<std::string> module, target;
	bool isModule = true;

	std::ifstream infile (argv[3], std::ios_base::in);
	while (getline(infile, line, '\n'))
	{
		if (line.empty())
			continue;

		if (isModule)
			module.push_back(line);
		else
			target.push_back(line);

		isModule = !isModule;
	}

	int result = 0;

	if (target.empty())
	{
		// failed
		result = -1;
	}
	else
	{
		// wait until updater is closed
		FILE *f;
		do {
			f = fopen(argv[1], "w+");
		} while (!f);
		fclose(f);

		// install
		for (int i = 0; i < target.size(); i++)
		{
			int res = unzipAll(module.at(i).c_str(), target.at(i).c_str());
			if (res < 0)	// failed
			{
				result = -2;
			}
		}
	}

	// start updater
	std::string params(argv[2]);
	params += " /i ";
	switch (result)
	{
	case -1:
		params += "/res:failed";
		break;
	case -2:
		params += "/res:unzip_failed";
		break;
	default: 
		params += "/res:ok";
	}

	ShellExecuteA(NULL, "open", argv[1], params.c_str(), NULL, SW_SHOW);

	return result;
}
